import store from '@/store'
import configs from '@/config'
import errorCode from '@/utils/errorCode.js'
import {
	Toast
} from '@/utils/actions.js'
import {
	TansParams
} from './tools'
// 获取登录信息
import { getStortLogin } from '@/utils/tools.js'
let timeout = 10000
const request = async config => {
	let baseUrl = configs[config.urlKey || 'baseUrl']
	config.header = config.header || {}
	let token = store.state.user.token;
	if (!store.state.user.token) {
		let data = await getStortLogin()
		// console.log(11111111111111, data.token) 
		token = data.token
		// console.log( '----store.state.user')
	}
	let shopid = store.state.user.userInfo.id;
	// console.log( '----store.state.user')
	if (token) {
		// debugger
		config.header['token'] = token;
		config.header['shopid'] = shopid;
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + TansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	// 检查请求地址中是否包含'undefined'，以防止因未定义的参数导致的非法请求
	if (config.url.indexOf('undefined') != -1) {
		// if (config.url.includes('undefined')) {
		// 输出错误信息到控制台，包括非法请求地址和阻断操作
		console.error('非法请求地址, 阻断', config.url);
		// 记录详细的日志信息
		console.error('配置信息:', config);
		// 结束函数执行，防止后续操作使用非法地址
		return;
	}
	return new Promise((resolve, reject) => {
		const requestParams = {
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json'
		}
		if (config.responseType) {
			requestParams.responseType = config.responseType;
		}
		uni.request(requestParams).then(async response => {
			const {
				data
			} = response
			const code = data.code
			const msg = errorCode[code] || data.msg || errorCode['default']
			// console.log(data, code)
			if (code === 401) {
				reject({
					error: 'ERR_401'
				})
				uni.redirectTo({
					url: `/pages/login/login`,
					success: res => {},
					fail: () => {},
					complete: () => {}
				})
			} else if (code === 0) {
				Toast.alert(msg)
				console.log(msg)
				reject('500')
			} else if (code === 4001) {
				Toast.alert(msg)
				reject(code)
			} else if (code === 4002) {
				Toast.alert(msg)
				reject(code)
			} else if (code === 4003) {
				uni.$emit('refresherDynamicList')
				reject(code)
			} else if (code !== 1) {
				Toast.alert(msg)
				reject(data)
			}
			resolve(data)
		}, (error) => {
			console.log('捕获error', error)
			let {
				message
			} = error
			if (message === 'Network Error') {
				message = '服务暂不可用，请稍后再试'
			} else if (message.includes('timeout')) {
				message = '系统接口请求超时'
			} else if (message.includes('Request failed with status code')) {
				message = '系统接口' + message.substr(message.length - 3) + '异常'
			}
			Toast.alert(message)
			reject(error)
		})
	})
}

export default request